import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index.js'
import { staticRouter, errorRouter } from './staticRouter.js'

import { dynamicRouter } from './dynamicRouter.js'
import initiDynamicRouter from './dynamicRouter2.js'

Vue.use(VueRouter)

// 初始化时 只加载静态路由和错误路由
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [...staticRouter, ...errorRouter]
})

// router.addRoutes(initiDynamicRouter)

// 替换路由
const newRouter = new VueRouter({
  routes: [...staticRouter, ...errorRouter]
})

router.beforeEach(async (to, from, next) => {
  // 没有tokens 跳转到登录页面
  if (!store.state.userToken.token) {
    console.log('登录')

    next()
    return
  }
  next()
})

// 重置路由
export function resetRouter() {
  /**
    route4的方法
    let routes = store.state.userAuth.userFinallyMenus
    routes.forEach(route => {
      const { name } = route
      if (name && router.hasRoute(name)) router.removeRoute(name)
    })
   */
  // route3方法
  router.matcher = newRouter.matcher
}

export default router
